<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryRef" :inline="true" :model="queryParams" label-width="110px">
      <el-form-item label="老人姓名：" prop="elderName" style="width: 250px">
        <el-input v-model="queryParams.elderName" clearable placeholder="请输入" @keyup.enter="handleQuery"/>
      </el-form-item>
      <el-form-item label="护理员姓名：" prop="nurseId" style="width: 250px">
        <el-select v-model="queryParams.nurseId" clearable placeholder="请选择">
          <el-option v-for="item in nurseList" :key="item.userId" :label="item.nickName" :value="item.userId">
            {{ item.nickName }}
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="护理项目：" prop="projectId" style="width: 250px">
        <el-select v-model="queryParams.projectId" clearable placeholder="请选择">
          <el-option v-for="item in nursingProjectOptions" :key="item.value" :label="item.label" :value="item.value">
            {{ item.label }}
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="期望服务时间：" prop="timeData" style="width: 400px">
        <el-date-picker v-model="queryParams.timeData" clearable date-format="YYYY/MM/DD ddd"
                        end-placeholder="结束时间" format="YYYY-MM-DD HH:mm:ss" start-placeholder="开始时间"
                        time-format="A hh:mm:ss" type="datetimerange" value-format="YYYY-MM-DD HH:mm:ss"
                        @change="handleTimeData"/>
      </el-form-item>
      <el-form-item>
        <el-button icon="Search" type="primary" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- tab导航 -->
    <div class="marg-main newBox">
      <SwitchBar ref="tabBar" :data="arrangeTabData" @change-id="changeId"></SwitchBar>
    </div>
    <!-- 表格 -->
    <el-table v-loading="loading" :data="nursingTaskDataList">
      <el-table-column align="center" label="序号" type="index" width="55"/>
      <el-table-column align="center" label="老人姓名" prop="elderName" width="150"/>
      <el-table-column align="center" label="床位号" prop="bedNumber" width="150"/>
      <el-table-column align="center" label="护理项目名称" prop="projectName" width="200"/>
      <el-table-column align="center" label="项目类型" prop="taskType" width="180">
        <template #default="scope">{{ scope.row.taskType === 2 ? '护理计划内' : '护理计划外' }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="护理员姓名" prop="nursingName" width="220"/>
      <el-table-column align="center" label="期望服务时间" prop="estimatedServerTime" width="200"/>
      <el-table-column align="center" label="创建时间" prop="createTime" width="180"/>
      <el-table-column align="center" fixed="right" label="操作" width="300">
        <template #default="scope">
          <el-button v-if="scope.row.status === 1" icon="CircleClose" link type="primary"
                     @click="handleCancel(scope.row)">取消
          </el-button>
          <el-button icon="View" link type="primary" @click="handleCheck(scope.row)">查看</el-button>
          <el-button v-if="scope.row.status === 1" :class="scope.row.count ? 'disabled' : ''" icon="Edit" link
                     type="primary" @click="handleExecute(scope.row)">执行
          </el-button>
          <el-button v-if="scope.row.status === 1" :class="scope.row.count ? 'disabled' : ''" icon="Tickets" link
                     type="primary" @click="handleChangeDate(scope.row)">改期
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageNum"
                :total="total" @pagination="getList"/>
    <!-- 取消弹窗 -->
    <CancelDialogFrom ref="formRef" :data="formBaseData" :title="title" :visible="visible" @handle-close="handleClose"
                      @handle-edit-form="handleEditForm"/>
    <!-- 执行弹层 -->
    <DialogFormExecute ref="formRef" :visible="dialogVisibleExecute" @handle-close="handleClose"
                       @handle-submit="handleSubmit"/>
    <!-- 改期弹层 -->
    <DialogFormTime :timeData="timeData" :visible="dialogVisible" @handle-close="handleClose"
                    @handle-submit="handleSubmitTime"/>
  </div>
</template>

<script name="AlertData" setup>

import {cancelPlan, changePlanTime, executePlan, listNursingTask} from '@/api/nursing/task';
import {getAllUserList} from '@/api/system/user';
import {getAllProjects} from '@/api/nursing/project';
import dayjs from 'dayjs';
import SwitchBar from '@/components/switchBar/switchBar.vue';
import CancelDialogFrom from './components/CancelDialogFrom.vue';
import DialogFormExecute from './components/DialogFormExecute.vue';
import DialogFormTime from './components/DialogFormTime.vue'
import {arrangeTabData} from '@/utils/commonData';

const {proxy} = getCurrentInstance();
const router = useRouter();
const nursingTaskDataList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const total = ref(0);
const title = ref('');
const visible = ref(false);
const dialogVisible = ref(false);
const dialogVisibleExecute = ref(false);
const disposeId = ref('');
const formRef = ref(null);
const taskId = ref(null);
const timeData = ref('')
const nurseList = ref([]);
const nursingProjectOptions = ref([]);
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
  },
  rules: {
    deviceName: [
      {required: true, message: '设备名称不能为空', trigger: 'blur'},
    ],
  },
});

const {queryParams, form, rules} = toRefs(data);

/** 查询报警数据列表 */
function getList() {
  loading.value = true;
  if (queryParams.value.status == '' || queryParams.value.status == null) {
    queryParams.value.status = 1;
  }
  listNursingTask(queryParams.value).then((response) => {
    nursingTaskDataList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

//处理时间
const handleTimeData = (val) => {
  console.log(val);
  if (val) {
    // queryParams.value.startTime = new Date(queryParams.value.timeData[0]).getTime();
    queryParams.value.startTime = val[0];
    queryParams.value.endTime = val[1];
  } else {
    queryParams.value.startTime = null;
    queryParams.value.endTime = null;
  }
};

const handleCancel = (row) => {
  visible.value = true;
  taskId.value = row.id;
};

const handleClose = () => {
  visible.value = false;
  dialogVisible.value = false;
  dialogVisibleExecute.value = false;
};

const handleEditForm = async (val) => {
  const res = await cancelPlan({...val, ...{taskId: taskId.value}});
  if (res.code === 200) {
    proxy.$modal.msgSuccess('编辑成功');
    getList();
    handleClose();
    formRef.value.handleClear();
  }
};

const handleExecute = (row) => {
  dialogVisibleExecute.value = true;
  taskId.value = row.id;
};

const handleSubmit = async (val) => {
  const res = await executePlan({
    ...val,
    ...{taskId: taskId.value},
    ...{
      estimatedServerTime: dayjs(val.estimatedServerTime).format(
          'YYYY-MM-DD HH:mm:ss'
      ),
    },
  });
  if (res.code === 200) {
    proxy.$modal.msgSuccess('执行成功');
    getList();
    handleClose();
    formRef.value.handleClear();
  } else {
    proxy.$modal.msgError(res.msg);
  }
};

const handleChangeDate = (row) => {
  dialogVisible.value = true
  taskId.value = row.id
  timeData.value = row.estimatedServerTime
}

const handleSubmitTime = async (val) => {
  const res = await changePlanTime({...val, ...{taskId: taskId.value}})
  if (res.code === 200) {
    proxy.$modal.msgSuccess('修改成功')
    getList()
    handleClose()
  } else {
    proxy.$modal.msgError(res.msg)
  }
}

const getAllUserListFunc = async () => {
  const res = await getAllUserList({deptId: '201'});
  nurseList.value = res.data;
};

const getAllProjectList = () => {
  getAllProjects().then((res) => {
    nursingProjectOptions.value = res.data;
  });
};

/** 搜索按钮操作 */
function handleQuery() {

  queryParams.value.pageNum = 1;
  queryParams.value.pageSize = 10;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm('queryRef');
  queryParams.value = {};
  handleQuery();
}

// 获取tab索引值
const changeId = (val) => {
  console.log(val);
  queryParams.value.pageNum = 1;
  queryParams.value.status = val;
  getList();
};

// 查看
const handleCheck = (val) => {
  router.push({
    path: `/nursing/arrangeDetails`,
    query: {
      id: val.id,
    },
  });
};
getList();
getAllUserListFunc();
getAllProjectList();
</script>
